package com.aizhixin.lab.project.template.controller;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.account.service.AccountService;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.PageData;
import com.aizhixin.lab.common.utils.TokenUtil;
import com.aizhixin.lab.config.Config;
import com.aizhixin.lab.project.template.data.NewProjectData;
import com.aizhixin.lab.project.template.data.ProjectData;
import com.aizhixin.lab.project.template.domain.ModuleTaskDomain;
import com.aizhixin.lab.project.template.domain.ProjectDomain;
import com.aizhixin.lab.project.template.domain.QueryProjectDomain;
import com.aizhixin.lab.project.template.entity.Project;
import com.aizhixin.lab.project.template.service.ProjectService;
import io.swagger.annotations.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/api/v1/project")
@RestController
@Api(tags = "项目上传", value = "项目")
public class ProjectController {
    @Autowired
    private ProjectService projectService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private Config config;

    @RequestMapping(value = "/exportProject", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "导出项目", httpMethod = "GET", notes = "导出项目<br><br><b>lwq</b>")
    public ResponseEntity<?> exportProject(@RequestHeader("Authorization") String token,@RequestParam String projectId, HttpServletResponse response) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        HSSFWorkbook wb = projectService.exportProject(projectId);
        FileOutputStream output = new FileOutputStream(config.getBaseDir() + "/vid.xlsx");
        wb.write(output);
        output.flush();
        String basePath = config.getBaseDir() + "/vid.xlsx";
        File file = new File(basePath);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xlsx", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();

        return new ResponseEntity(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/importProject", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "导入项目", httpMethod = "POST", notes = "导入项目<br><br><b>lwq</b>")
    public ResponseEntity<?> importProject(@RequestHeader("Authorization") String token,
                                           @ApiParam(value = "Excel数据文件", required = true) @RequestParam(value = "file") MultipartFile file) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        projectService.importProject(file,account.getId());
        result.put(ApiReturnConstants.SUCCESS,true);
        return new ResponseEntity(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/importEasyProject", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "导入项目(简易版)", httpMethod = "POST", notes = "导入项目(简易版)<br><br><b>lwq</b>")
    public ResponseEntity<?> importEasyProject(@RequestHeader("Authorization") String token,
                                           @ApiParam(value = "Excel数据文件", required = true) @RequestParam(value = "file") MultipartFile file) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }


        try {
          result= projectService.importEasyProject(file,account.getId());
        }catch (Exception e){
            result.put(ApiReturnConstants.SUCCESS,false);
            result.put(ApiReturnConstants.MESSAGE,e.getMessage());
        }

        return new ResponseEntity(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "保存", httpMethod = "POST", notes = "保存/编辑<br><br><b>lwq</b>")
    public ResponseEntity<?> save(@RequestHeader("Authorization") String token, @RequestBody ProjectDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }

        Project save = projectService.save(domain,account.getId());
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, save.getId());

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "编辑", httpMethod = "POST", notes = "保存/编辑<br><br><b>lwq</b>")
    public ResponseEntity<?> update(@RequestHeader("Authorization") String token, @RequestBody ProjectDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        try {
            result = projectService.updateProject(domain);
        } catch (Exception e) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, e.getMessage());
        }

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findProject", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "项目首页查询", httpMethod = "POST", notes = "项目首页查询<br><br><b>lwq</b>")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProjectDomain.class),})
    public ResponseEntity<?> findProject(@RequestHeader("Authorization") String token,
                                         @RequestBody QueryProjectDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        try {
            result = projectService.findProject(domain,null);
            result.put(ApiReturnConstants.SUCCESS, true);
        } catch (Exception e) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, e.getMessage());
        }

        return new ResponseEntity(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/findTeaProject", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "老师查询自建项目", httpMethod = "POST", notes = "老师查询自建项目<br><br><b>lwq</b>")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProjectDomain.class),})
    public ResponseEntity<?> findTeaProject(@RequestHeader("Authorization") String token,
                                         @RequestBody QueryProjectDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        try {
            result = projectService.findProject(domain,account.getId());
//            result.put(ApiReturnConstants.SUCCESS, true);
//            result.put(ApiReturnConstants.DATA, result);
        } catch (Exception e) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, e.getMessage());
        }

        return new ResponseEntity(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/findProjectInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查看项目详情", httpMethod = "GET", notes = "查看项目详情<br><br><b>lwq</b>")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ProjectDomain.class),})
    public ResponseEntity<?> findProjectInfo(@RequestHeader("Authorization") String token, @RequestParam(name = "id") String id) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }

        NewProjectData projectDomain = projectService.findProjectDomain(id);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, projectDomain);

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/publish", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "发布/取消发布项目", httpMethod = "GET", notes = "更改项目发布状态<br><br><b>lwq</b>")
    public ResponseEntity<?> publish(@RequestHeader("Authorization") String token, @RequestParam String id) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        result = projectService.publish(id);

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除项目", httpMethod = "GET", notes = "删除项目<br><br><b>lwq</b>")
    public ResponseEntity<?> delete(@RequestHeader("Authorization") String token, @RequestParam String id) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        result = projectService.delete(id);
        return new ResponseEntity(result, HttpStatus.OK);
    }
}
